package org.zhangkun.jmsg.ui.swing.view;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LinearGradientPaint;
import java.awt.geom.Point2D;

import javax.swing.JComponent;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicPanelUI;

import sun.awt.AppContext;

public class GradientPanelUI extends BasicPanelUI {

	public static ComponentUI createUI(JComponent c) {
		AppContext appContext = AppContext.getAppContext();
		GradientPanelUI compUI = (GradientPanelUI) appContext
				.get(GradientPanelUI.class.getSimpleName());
		if (compUI == null) {
			compUI = new GradientPanelUI();
			appContext.put(GradientPanelUI.class.getSimpleName(), compUI);
		}
		return compUI;
	}

	@Override
	public void update(Graphics g, JComponent c) {

		float fractions[] = new float[] { 0.3f, 0.7f };

		Color colors[] = new Color[] { Color.WHITE, new Color(200, 200, 255) };

		paintGradientBackground(g, c, fractions, colors);

		c.setOpaque(false);
		super.paint(g, c);

	}

	static public void paintGradientBackground(Graphics g, JComponent c,
			float[] fractions, Color[] colors) {
		if (c == null || fractions == null || colors == null || g == null) {
			System.err.println("有参数为空，无法绘制!");
			return;
		}

		Graphics2D g2d = (Graphics2D) g;
		Dimension d = c.getSize();

		// 使用GradientPaint 的情况
		// GradientPaint paint = new
		// GradientPaint(0,0,Color.WHITE,0,d.height/4,Color.green,true);

		// 线性渐进色
		// 默认渐进方式：从左上至右下
		Point2D start = new Point2D.Float(0, 0);
		Point2D end = new Point2D.Float(d.width, d.height);

		LinearGradientPaint lpaint = new LinearGradientPaint(start, end,
				fractions, colors);

		g2d.setPaint(lpaint);
		g2d.fillRect(0, 0, d.width, d.height);

	}
}